<?php
header('Content-Type: application/vnd.ms-excel;charset=utf-8');
ob_start();
set_time_limit(0);
define('ORG_ID', 'cqyx_hw');
include("../../nncms_manager_inc.php");
include_once LOGIC_DIR . 'log' . DIRECTORY_SEPARATOR . 'manager_log.class.php';
include_once LOGIC_DIR . 'video' . DIRECTORY_SEPARATOR . 'vod_media.class.php';
include_once LOGIC_DIR . 'video' . DIRECTORY_SEPARATOR . 'vod_index.class.php';
include_once $nncms_config_path . 'mgtv_v2' . DIRECTORY_SEPARATOR . 'mgtv_init.php';
include_once $nncms_config_path . 'mgtv_v2' . DIRECTORY_SEPARATOR . 'models' . DIRECTORY_SEPARATOR . 'queue_task_model.php';
//导入语言包
if (isset($_POST["language_dir"]))
{
    $language_dir=$_POST["language_dir"];
}
include $nncms_config_path . "nn_cms_manager/languages/" . $language_dir . "/language.php";
$org_id = $_POST["nns_org_id"];
$org_type = $_POST["nns_org_type"];
$sp_id = $_POST['sp_id'];

$targetFolder = dirname(__FILE__);
$verifyToken = md5('unique_salt' . $_POST['timestamp']);
$action =null;
if($_REQUEST['nns_action'] == 'download')
{
    if(isset($_GET['file_path']))
    {
        $file_path = $_GET['file_path'];
        $file_path = urldecode($file_path);
        download_error_media_message($file_path);
    }
    else
    {
        $date = date('Ymd');
        $base_file_dir = dirname(dirname(dirname(dirname(__FILE__))))."/data/download_file/{$date}";
        $result = get_files($base_file_dir);
        if($result['ret'] !=0)
        {
            echo "<script>alert("+$result['reason']+");</script>";die;
        }
        download_error_media_message($result['data']);
    }
    die;
}
if($_POST['nns_action'] == 'delete_old')
{
    $action = 'delete_old';
    $file_path = $nncms_config_path . 'data' . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR . 'op_queue' . DIRECTORY_SEPARATOR . "$sp_id" . DIRECTORY_SEPARATOR. 'delete_media_task.txt';
}
else
{
    $file_path = $nncms_config_path . 'data' . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR . 'op_queue' . DIRECTORY_SEPARATOR . 'delete_vod_task.txt';
}

if (!empty($_FILES) && $_POST['token'] == $verifyToken)
{
    try
    {
        echo file_import_to_txt($_FILES['Filedata']['tmp_name']);
    }
    catch (Exception $e)
    {
        echo 'csv文件格式错误';
    }
}

/**
 * 将要删除的数据整理好放入txt文件中，给计划任务备用
 * @param string $upload_file 上传文件路径
 * @param string $sp_id SP ID
 * @param string $file_path txt文件路径
 * @return string
 * @author chunyang.shu
 * @date 2015-03-02
 */
function file_import_to_txt($upload_file)
{
    $upload_file = fopen($upload_file, 'r');
    $dc = nl_get_dc(array (
        'db_policy' => NL_DB_READ,
    ));
    $dc->open();
    $data=array();
    $queue_task_model = new queue_task_model();
    $num = 0;
    $first = false;
    $flag = true;
    while (!feof($upload_file))
    {
        $line_arr = fgetcsv($upload_file);
        if($first === false)
        {
            unset($first);
            continue;
        }
        if (is_array($line_arr) && !empty($line_arr))
        {
            $file_name = substr($line_arr[0],0,-3);
            $sql = "select * from nns_vod_media where nns_media_name ='$file_name'";
            $check_result = nl_query_by_db($sql, $dc->db());
            if(is_array($check_result) && !empty($check_result))
            {
                $queue_task_model->cqyx_stock_import(ORG_ID,$check_result[0]['nns_id'],$check_result[0]['nns_vod_index_id'],$check_result[0]['nns_vod_id']);
            }
            else
            {
                $flag = false;
                $num++;
                $data[] = array($num,$line_arr[0]);
            }
        }
    }
    fclose($upload_file);
    ob_clean();
    ob_flush();
    unset($upload_file);
    $date = date('Ymd');
    $filename = date('His')."_queue_list.csv";
    $save_file_path = dirname(dirname(dirname(dirname(__FILE__))))."/data/download_file/{$date}/";
    $csv_save_file_path = dirname(dirname(dirname(dirname(__FILE__))))."/data/download_file/{$date}/".$filename ;
    if (!empty($save_file_path) && !is_dir($save_file_path))
    {
        $flg = mkdir($save_file_path, 0777, true);
        //递归创建
        if (!$flg)
        {
            return 'failed make folder';
        }
    }
    else
    {
        @chmod($save_file_path, 0777);
    }
    header("Content-Disposition: attachment;filename=". $filename);
    header('Cache-Control: max-age=0');
// 	print(chr(0xEF).chr(0xBB).chr(0xBF));
    ob_start();
    $fp = fopen($csv_save_file_path, 'a');
    export_media_csv($fp,array('NUMBER','MEDIANAME'));
    foreach($data as $val)
    {
        export_media_csv($fp, $val);
    }
    $array = array(
        'ret'=>1,
        'info'=>'',
        'file'=>urlencode($csv_save_file_path)
    );
    if($flag === false)
    {
        $array['ret'] = 0;
        $array['info'] = "<font color='green'>部分数据处理失败,请下载csv数据</font><script>alert('部分数据处理失败,请下载csv数据')</script>";
    }
    else
    {
        $array['info'] = "<font color='red'>全部处理成功</font><script>alert('全部处理成功')</script>";
    }
    return json_encode($array);
}

function get_files($base_file_dir)
{
    if(!is_dir($base_file_dir))
    {
        return array(
            'ret'=>1,
            'reason'=>'文件路径错误'
        );
    }
    $arr_base_file_dir = scandir($base_file_dir);
    $arr_base_file_dir = array_diff($arr_base_file_dir, array('.','..'));
    if(!is_array($arr_base_file_dir) || empty($arr_base_file_dir))
    {
        return array(
            'ret'=>1,
            'reason'=>'查无文件'
        );
    }
    foreach ($arr_base_file_dir as $afile)
    {
        if (is_dir($base_file_dir . '/' . $afile))
        {
            continue;
        }
        $pathinfo_file = pathinfo($afile);
        if(isset($pathinfo_file['extension']) && $pathinfo_file['extension']=='csv' && isset($pathinfo_file['filename']) && strlen($pathinfo_file['filename']) > 0)
        {
            $arr_temp_base_file_dir[] = $base_file_dir.'/'.$afile;
            $arr_temp_base_file_dir_1[] = get_file_date($base_file_dir.'/'.$afile);
        }
    }
    if(empty($arr_temp_base_file_dir))
    {
        return array(
            'ret'=>1,
            'reason'=>'查无文件'
        );
    }
    array_multisort($arr_temp_base_file_dir,$arr_temp_base_file_dir_1);
    return array(
        'ret'=>1,
        'reason'=>'有文件',
        'data'=>array_pop($arr_temp_base_file_dir)
    );
}

function get_file_date($file_path)
{
    $date_time=filemtime($file_path);
    if($date_time === false)
    {
        $date_time = 0;
    }
    return $date_time;
}

function export_media_csv($fp,$data)
{
    if(empty($data) || !is_array($data))
    {
        return ;
    }
    fputcsv($fp, $data);
    unset($data);
    return ;
}

function download_error_media_message($file_path)
{
    if(!file_exists($file_path))
    {
        return '下载的文件不存在';
    }
    else
    {
        $basename = basename($file_path);
        //打开文件
        $file = fopen ( $file_path, "r" );
        //输入文件标签
        Header ( "Content-type: application/octet-stream" );
        Header ( "Accept-Ranges: bytes" );
        Header ( "Accept-Length: " . filesize ( $file_path ) );
        Header ( "Content-Disposition: attachment; filename=" . $basename );
        echo fread ( $file, filesize ( $file_path ) );
        fclose ( $file );
        exit ();
    }
}
